import time
import execjs
import requests
import pandas as pd
import os
import time
from concurrent import futures

from DataSource.DistributionOfChips.Analysis import submit_analysis

# start_time=time.time()
os.environ["EXECJS_RUNTIME"] = "Node"
print(execjs.get().name)
current_dir = os.path.dirname(os.path.realpath(__file__))

with open(current_dir+'/cal_jetton.js', 'r', encoding='utf-8') as f:
    js_text = f.read()

def find_HL(deal_with):
    max=-1*1000
    min=10000000
    # print(deal_with)
    for row in deal_with[-68:]:
        # print(row[0])
        h,l=row[3],row[4]

        if h>max:
            max=h
            # print(row[0],h)
        if l<min:
            min=l
            # print(row)
            # print(l)
    # print(max,min)
    return max,min

def jquery_list(jquery, data_mode='['):
    reverse_mode = {'[': ']', '{': '}', '(': ')'}
    tail_str = jquery[-5:][::-1]
    return eval(jquery[jquery.index(data_mode): -tail_str.index(reverse_mode[data_mode])])


def save_data(data, file_name, header=True):
    data = pd.DataFrame(data)
    if header:
        data.to_csv(f'{file_name}.csv', encoding='gbk', header=header, index=False, mode='a')
    else:
        data.to_csv(f'{file_name}.csv', encoding='gbk', header=header, index=False, mode='a')

def getJson(url,headers):
    try:
        response = requests.request("GET", url, headers=headers)
        return response
    except Exception as e:
        print(e)
        time.sleep(2)
        return getJson(url,headers)

df = pd.read_csv(current_dir+'/data_csv/2022-09-22-个股.csv', encoding='gbk')

step = 1
def getOneStock(i):
    global step
    # i = "002518.SZ"
    print(i)

    if i[0] == '6':
        bourse_code = '1.' + i[:6]
    elif i[0] in ('0', '3'):
        bourse_code = '0.' + i[:6]
    else:
        # continue
        return
    url = "http://push2his.eastmoney.com/api/qt/stock/kline/get?cb=jQuery1124011839104433800074_1663654201455&fields1" \
          "=f1,f2,f3,f4,f5,f6&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&ut=7eea3edcaed734bea9cbfc24409ed989" \
          f"&klt=101&fqt=1&secid={bourse_code}&beg=0&end=20500000&_={int(time.time() * 1000)}"

    headers = {
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Referer': 'http://quote.eastmoney.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
                      ' Chrome/103.0.0.0 Safari/537.36'
    }

    response = getJson(url, headers)

    deal_with = []
    # print(response.text)
    for y in jquery_list(response.text, data_mode='['):
        temp = []
        for x in y.split(','):
            if '-' == x[0]:
                temp.append(eval(x))
            elif '-' in x:
                temp.append(x)
            else:
                temp.append(eval(x))
        deal_with.append(temp)
    # print(deal_with)
    maxx, minx = find_HL(deal_with)
    print(maxx, minx)
    # break

    try:
        cm = execjs.compile(js_text)
        r = cm.call('get', deal_with)
        print(r)
        date = r['date']
        data = {'日期': [date], '股票代码': [i], '获利比例': [r['profit']], '平均成本': [r['avg_cost']],
                '90%成本': [r['cost_90']], '90%集中度': [r['ratio_90']], '70%成本': [r['cost_70']],
                '70%集中度': [r['ratio_70']], 'max': [maxx], 'min': [minx]}
        print(date)
        print(current_dir+'/data_csv/{date}筹码分布')
        if step == 1:
            save_data(data=data, file_name=current_dir+'/data_csv/'+date+'筹码分布')
        else:
            save_data(data=data, file_name=current_dir+'/data_csv/'+date+'筹码分布', header=False)
        step += 1
    except execjs._exceptions.ProgramError as e:
        print(e)
        # continue
        return
        # break

def mutil_workers():
    with futures.ThreadPoolExecutor(max_workers=5) as executor:
        for i in df['股票代码'].values:
            # time.sleep(0.2)
            executor.submit(getOneStock, i)  #
        # break

def test_schedule():
    print('guava')
import schedule
schedule.every().day.at("15:01").do(mutil_workers)
schedule.every().day.at("15:20").do(submit_analysis)

# submit_analysis()
while True:
    schedule.run_pending()
    time.sleep(1)